"""
文件上传路由
"""
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, status
from fastapi.responses import FileResponse
from typing import List
import os
from pathlib import Path

from utils.dependencies import get_current_user
from models.user import User
from services.file_upload_service import FileUploadService
from config import settings

router = APIRouter(tags=["文件上传"])


@router.post("/upload/image")
async def upload_image(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """上传图片文件（用于编辑器）"""
    try:
        result = await FileUploadService.upload_image(file, current_user.id)
        return {
            "success": True,
            "message": "图片上传成功",
            "data": result
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"图片上传失败: {str(e)}"
        )


@router.post("/upload/attachment")
async def upload_attachment(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """上传附件文件"""
    try:
        print(f"开始上传附件: {file.filename}, 用户ID: {current_user.id}")
        print(f"文件大小: {file.size}, 文件类型: {file.content_type}")

        result = await FileUploadService.upload_attachment(file, current_user.id)

        print(f"附件上传成功: {result}")
        return {
            "success": True,
            "message": "附件上传成功",
            "data": result
        }
    except HTTPException as e:
        print(f"HTTPException in upload_attachment: {e.detail}")
        raise e
    except Exception as e:
        print(f"Exception in upload_attachment: {str(e)}")
        import traceback
        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"附件上传失败: {str(e)}"
        )


@router.post("/upload/datasource")
async def upload_datasource(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """上传数据源文件"""
    try:
        result = await FileUploadService.upload_datasource(file, current_user.id)
        return {
            "success": True,
            "message": "数据源文件上传成功",
            "data": result
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"数据源文件上传失败: {str(e)}"
        )


@router.post("/upload/multiple")
async def upload_multiple_files(
    files: List[UploadFile] = File(...),
    file_type: str = "attachment",  # image, attachment, datasource
    current_user: User = Depends(get_current_user)
):
    """批量上传文件"""
    try:
        results = []
        errors = []

        for file in files:
            try:
                if file_type == "image":
                    result = await FileUploadService.upload_image(file, current_user.id)
                elif file_type == "attachment":
                    result = await FileUploadService.upload_attachment(file, current_user.id)
                elif file_type == "datasource":
                    result = await FileUploadService.upload_datasource(file, current_user.id)
                else:
                    raise HTTPException(
                        status_code=status.HTTP_400_BAD_REQUEST,
                        detail=f"不支持的文件类型: {file_type}"
                    )
                
                results.append(result)
                
            except Exception as e:
                errors.append({
                    "filename": file.filename,
                    "error": str(e)
                })
        
        return {
            "success": len(errors) == 0,
            "message": f"成功上传 {len(results)} 个文件" + (f"，{len(errors)} 个文件失败" if errors else ""),
            "data": {
                "success_files": results,
                "failed_files": errors
            }
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"批量上传失败: {str(e)}"
        )


@router.get("/download/{file_type}/{filename}")
async def download_file(
    file_type: str,
    filename: str,
    current_user: User = Depends(get_current_user)
):
    """下载文件"""
    try:
        # 验证文件类型
        if file_type not in ["images", "attachments", "datasources"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="无效的文件类型"
            )

        # 构建文件路径
        file_path = Path(settings.upload_dir) / f"user_{current_user.id}" / file_type / filename
        
        # 检查文件是否存在
        if not file_path.exists():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="文件不存在"
            )
        
        # 获取文件信息
        file_info = FileUploadService.get_file_info(str(file_path))
        if not file_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="无法获取文件信息"
            )
        
        # 返回文件
        return FileResponse(
            path=str(file_path),
            filename=filename,
            media_type=file_info.get("content_type", "application/octet-stream")
        )
        
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件下载失败: {str(e)}"
        )


@router.delete("/delete/{file_type}/{filename}")
async def delete_file(
    file_type: str,
    filename: str,
    current_user: User = Depends(get_current_user)
):
    """删除文件"""
    try:
        # 验证文件类型
        if file_type not in ["images", "attachments", "datasources"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="无效的文件类型"
            )

        # 构建文件路径
        file_path = Path(settings.upload_dir) / f"user_{current_user.id}" / file_type / filename
        
        # 删除文件
        success = FileUploadService.delete_file(str(file_path))
        
        if success:
            return {
                "success": True,
                "message": "文件删除成功"
            }
        else:
            return {
                "success": False,
                "message": "文件删除失败或文件不存在"
            }
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件删除失败: {str(e)}"
        )


@router.get("/list/{file_type}")
async def list_files(
    file_type: str,
    current_user: User = Depends(get_current_user)
):
    """获取文件列表"""
    try:
        # 验证文件类型
        if file_type not in ["images", "attachments", "datasources"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="无效的文件类型"
            )

        # 获取用户文件目录
        user_dir = Path(settings.upload_dir) / f"user_{current_user.id}" / file_type

        if not user_dir.exists():
            return {
                "success": True,
                "data": []
            }

        # 获取文件列表
        files = []
        for file_path in user_dir.iterdir():
            if file_path.is_file():
                file_info = FileUploadService.get_file_info(str(file_path))
                if file_info:
                    file_info["url"] = f"/uploads/user_{current_user.id}/{file_type}/{file_path.name}"
                    files.append(file_info)
        
        return {
            "success": True,
            "data": files
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取文件列表失败: {str(e)}"
        )
